package com.mms.service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.mms.dao.StatisticsMapper;
import com.mms.dao.UserMapper;
import com.mms.entity.CustomerState;
import com.mms.util.MyBatisUtilsPlus;

public class StatisticsServiceImpl implements StatisticsService {

	StatisticsMapper mapper = MyBatisUtilsPlus.getMapper(StatisticsMapper.class);
	UserMapper userMapper = MyBatisUtilsPlus.getMapper(UserMapper.class);
	
	@Override
	public List<Map<String, Object>> salesFunnel(String username, Date begin, Date end) {
		// 如何username是一个MANAGER角色的用户，需要基于他整个团队的客户来统计。
		// 所以首先查出username以及username的下属们，得到一个List<String>
		List<String> usernames = this.userMapper.selectUsernameByManager(username);
		usernames.add(username);
		List<Map<String, Object>> list = this.mapper.countByUsernameAndReportToDateGroupByState(usernames, begin, end);
		return list;
	}

	@Override
	public Map<String, String> conversionRate(String username, Date begin, Date end) {
		// 复用上面的方法，得到统计结果
		List<Map<String, Object>> list = this.salesFunnel(username, begin, end);
		// 从List中分别解析出各个状态的人数
		long unknown = 0, intentional = 0, dealed = 0;
		for (Map<String, Object> map : list) {
			CustomerState state = Enum.valueOf(CustomerState.class ,(String) map.get("state"));
			if(state == CustomerState.UNKNOWN) {
				unknown = (long) map.get("count");
			} else if (state == CustomerState.INTENTIONAL) {
				intentional = (long) map.get("count");
			} else {
				dealed = (long) map.get("count");
			}
		}
		// 总报备数 = 意向不明的人数 + 有意向的人数 + 成交数
		long 报备客户数 = unknown + intentional + dealed;
		// 总意向数 = 有意向的人数 + 成交数
		long 意向客户数 = intentional + dealed;
		long 成交客户数 = dealed;
		String 意向转化率 = String.format("%.2f", 100.0 * 意向客户数 / 报备客户数) + "%";
		String 成交转化率 = String.format("%.2f", 100.0 * 成交客户数 / 意向客户数) + "%";
		
		HashMap<String, String>	result = new HashMap<>();
		result.put("报备客户数", String.valueOf(报备客户数));
		result.put("意向客户数", String.valueOf(意向客户数));
		result.put("成交客户数", String.valueOf(成交客户数));
		result.put("意向转化率", 意向转化率);
		result.put("成交转化率", String.valueOf(成交转化率));
		return result;
	}

	@Override
	public List<Map<String, Object>> dealTrend(String username, Date begin, Date end) {
		List<String> usernames = this.userMapper.selectUsernameByManager(username);
		usernames.add(username);
		List<Map<String, Object>> list = this.mapper.countByUsernameAndDealDateGroupByYearMonth(usernames, begin, end);
		return list;
	}
	
	

}
